package wsepForum.common.elements;


import java.util.Vector;
import wsepForum.persistance.exceptions.InvalidElementFormatException;

/**
 * 
 * @author Ofir Tam & Ori Ossmy
 *
 */
public class Topic extends TopicHeader {

	/*****************************
	 * MEMBERS                   *
	 *****************************/	
	private Vector<Message> topicMessages;
	
	
	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/		
	public Topic() {
		super("", -1);
		this.topicMessages = new Vector<Message>();
	}
	
	/**
	 * 
	 * @param message
	 */
	public Topic(int id, Message message, int parentID) {
		super(message.getHeadLine(), parentID);
		this.setElementID(id);
		this.topicMessages = new Vector<Message>();
		this.addMessage(message);
	}

	/*****************************
	 * METHODS                   *
	 *****************************/	
	/**
	 * 
	 * @param message
	 */
	public void addMessage(Message message){
		this.handleMessages(message);
		message.setParentID(this.getElementID());
		if (this.topicMessages.size()==0){
			this.setHeadLine(message.getHeadLine());
		}
		this.topicMessages.add(message);
	}
	
	/**
	 * 
	 * @param message
	 */
	public boolean removeMessage(Message message){
		return (this.handleMessages(message)==0);
	}
	
	/**
	 * 
	 * @param index
	 * @return
	 * @throws InvalidElementFormatException 
	 */
	public Message getMessage(int index) throws InvalidElementFormatException{
		try 
		{
			return this.topicMessages.elementAt(index);
		}
		catch (ArrayIndexOutOfBoundsException e) 
		{
			throw new InvalidElementFormatException ("no message in this index - out of bounds exception");
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public Vector<Message> getAllMessages(){
		return this.topicMessages;
	}
	
	
	/**
	 * 
	 * @param headers
	 * @param newHeader
	 */
	private int handleMessages(Message newMessage) {
		boolean isContained = false;
		int removeIndex = -1;
		for (int tIndex = 0; ((!isContained)&&(tIndex < this.topicMessages.size())); tIndex++) {
			if (this.topicMessages.elementAt(tIndex).getElementID() == newMessage.getElementID()) {
				isContained=true;
				this.topicMessages.removeElementAt(tIndex);
				removeIndex = tIndex;
			}
		}
		return removeIndex;
	}
	
}
